<script>
  import { mapActions, mapMutations, mapState } from 'vuex'
  import { NOOP } from '@web-utils/core'
  import { getTenantList } from '@/api/login'
  import Verify from './verifition/Verify'
  import { getStore, removeStore, setStore } from '@/util/store'

  const users =
    process.env.NODE_ENV === 'production'
      ? []
      : [
          {
            name: '超级管理员',
            username: 'admin'
          },
          {
            name: '李岳',
            username: 'liyue',
            password: '123456'
          },
          {
            name: '李巍巍',
            username: 'liweiwei'
          }
        ]
  export default {
    name: 'Login',
    props: {
      pwd: String,
      uname: String
    },
    data() {
      return {
        showPopper: false,
        loading: false,
        rules: {
          username: [
            {
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            }
          ]
        },
        tenantList: [],
        tenantId: '1',
        entity: {
          username: 'admin',
          password: '',
          code: '',
          randomStr: 'blockPuzzle'
        }
      }
    },
    computed: {
      ...mapState('viewState', ['theme']),
      ...mapState('common', ['useVerifyCode'])
    },
    watch: {
      tenantId(newVal) {
        setStore('tenantId', newVal)
      }
    },
    async created() {
      removeStore('appName')
      removeStore('homeType')
      this.clearViewCache()
      const res = await getTenantList()
      this.tenantList = res.data.data
      this.tenantId = getStore('tenantId') || this.tenantId
    },
    mounted() {
      if (this.uname && this.pwd) {
        this.entity.username = this.uname
        this.entity.password = this.pwd
        this.submitForm()
      }
    },
    methods: {
      ...mapActions('user', ['handleLogin']),
      ...mapMutations('viewState', ['clearViewCache']),
      async submitForm(event) {
        if (event) {
          event.preventDefault()
        }
        if (process.env.NODE_ENV !== 'production') {
          if (!this.entity.password) {
            this.entity.password = '123456'
          }
        }

        const res = await this.$refs.form.validate()
        if (res) {
          if (this.useVerifyCode) {
            this.$refs.verify.show()
          } else {
            await this.loginByUsername()
          }
        }
      },
      async loginByUsername() {
        this.loading = true
        const username = this.entity.username
        const password = this.entity.password
        try {
          await this.handleLogin({
            username,
            password,
            grantType: 'password',
            randomStr: this.entity.randomStr,
            validCode: this.entity.code,
            auto: true
          })
          await this.$router.replace(this.$route.query.redirect || '/')
        } catch (e) {
          console.error(e)
          this.$message.error(e.message || '登录失败')
        }
        this.loading = false
      },
      genList() {
        return (
          <ul>
            {users.map((item, index) => (
              <li key={index} onClick={() => this.onItemClick(item)} class="login-user-item">
                <i class="el-icon-user-solid"></i> {item.name}
              </li>
            ))}
          </ul>
        )
      },
      onShow() {
        this.showPopper = true
      },
      genPopover() {
        return process.env.NODE_ENV === 'production' ? null : (
          <ElPopover
            show={this.onShow}
            placement="top"
            popperClass="custom-popover"
            trigger="click"
            vModel={this.showPopper}
            scopedSlots={{ default: this.genList }}
            width="290">
            <div class="float-btn" slot="reference" v-show="!loading">
              <i class="el-icon-user"></i>
            </div>
          </ElPopover>
        )
      },
      genBuiltOn() {
        return process.env.VUE_APP_BUILD_DATE ? (
          <span class="built-on" style="position:fixed;right:10px;bottom:10px;font-size:16px;">
            built on {process.env.VUE_APP_BUILD_DATE}
          </span>
        ) : null
      },
      onItemClick:
        process.env.NODE_ENV === 'production'
          ? NOOP
          : function (item) {
              this.showPopper = false
              this.entity.username = item.username
              this.entity.password = item.password
              this.submitForm()
            },
      async verifySuccess(params) {
        this.entity.code = params.captchaVerification
        await this.loginByUsername()
      }
    },
    render() {
      const { entity, rules, loading, submitForm, genPopover, genBuiltOn, tenantList } = this

      return (
        <div class="login-page">
          <div class="login-content">
            <div class="login-right flex-column">
              <h2 class="login-title">{process.env.VUE_APP_APP_NAME}</h2>
              <ElForm
                props={{
                  model: entity,
                  rules
                }}
                class="login-form"
                nativeOn={{ submit: submitForm }}
                label-width="0px"
                ref="form">
                {process.env.NODE_ENV !== 'production' ? (
                  <ElFormItem
                    class="login-form-item"
                    prop="username"
                    rules={[
                      {
                        required: true,
                        message: '请选择租户',
                        trigger: 'blur',
                        validator: (rule, value, callback) => {
                          if (!this.tenantId) {
                            callback(new Error('invalid'))
                          } else {
                            callback()
                          }
                        }
                      }
                    ]}>
                    <ElSelect disabled={loading} class="login-select" placeholder="请选择租户" vModel={this.tenantId}>
                      {tenantList.map(item => (
                        <ElOption value={item.code} label={item.name} />
                      ))}
                    </ElSelect>
                  </ElFormItem>
                ) : null}
                <ElFormItem class="login-form-item" prop="username">
                  <ElInput disabled={loading} class="login-input" placeholder="请输入用户名" vModel={entity.username}>
                    <template slot="prepend">
                      <i class="el-icon-user-solid"></i>
                    </template>
                  </ElInput>
                </ElFormItem>
                {this.useVerifyCode ? (
                  <ElFormItem class="login-form-item" prop="code" style="margin-bottom: 0;">
                    <Verify
                      onSuccess={this.verifySuccess}
                      mode="pop"
                      captchaType="blockPuzzle"
                      imgSize={{
                        width: '330px',
                        height: '155px'
                      }}
                      ref="verify"
                    />
                  </ElFormItem>
                ) : null}
                <ElFormItem class="login-form-item" prop="password">
                  <ElInput
                    disabled={loading}
                    class="login-input"
                    placeholder="请输入密码"
                    type="password"
                    vModel={entity.password}>
                    <template slot="prepend">
                      <i class="el-icon-unlock"></i>
                    </template>
                  </ElInput>
                </ElFormItem>
                <ElFormItem class="login-form-item">
                  <div class="login-btn-wrapper flex-item">
                    <ElButton loading={loading} class="login-btn" native-type="submit" type="primary">
                      登 录{loading ? ' 中...' : ''}
                    </ElButton>
                  </div>
                </ElFormItem>
              </ElForm>
            </div>
          </div>
          {genPopover()}
          {genBuiltOn()}
        </div>
      )
    }
  }
</script>

<style lang="scss">
  .custom-popover {
    border: 1px solid var(--border-color);

    .popper__arrow {
      border-top-color: gray;
    }

    .login-user-item {
      display: flex;
      align-items: center;
      padding: 14px 10px;
      font-size: 12px;
      cursor: pointer;

      .el-icon-user-solid {
        margin-right: 10px;
        font-size: 1.5em;
      }

      &.active,
      &:hover {
        background-color: #eee;
      }
    }
  }

  .login-page {
    width: 100%;
    height: 100%;
    background: url('~@/assets/images/login/peronnel_system.png') no-repeat 0 0;
    background-size: cover;

    .login-content {
      position: absolute;
      top: 20vh;
      left: 50%;
      z-index: 9;
      width: 1120px;
      height: auto;
      transform: translateX(-50%);
    }

    .login-title {
      display: block;
      margin-bottom: 2rem;
      color: #333;
      font-size: 22px;
      text-align: center;
    }

    .login-right {
      align-items: center;
      justify-content: center;
      float: right;
      width: 390px;
      height: 400px;
      background-color: #fff;
      border-radius: 3px;
      box-shadow: 0 7px 25px rgba(0, 0, 0, 0.08);
    }

    .login-section-title {
      display: none;
      margin: 20px 0 20px 5px;
      color: #131519;
      font-weight: bold;
      font-size: 16px;
      text-align: left;
    }

    .login-form {
      width: 310px;
    }

    .login-form-item {
      .el-form-item__content {
        display: flex;
      }

      .el-form-item__error {
        padding-left: 20px;
      }
    }

    .login-select {
      border: 1px solid var(--color-primary);
      border-radius: 4px;
      width: 100%;

      .el-input__inner {
        background: transparent;
        border: none;
        border-radius: 0;

        &:focus {
          border-color: transparent;
        }
      }
    }

    .login-input {
      border: 1px solid var(--color-primary);
      border-radius: 4px;

      .el-input-group__prepend {
        padding: 0 10px;
        background: transparent;
        border: 0;
        border: none;
        border-radius: 0;
      }

      .el-input__inner {
        padding: 0;
        letter-spacing: 0.3px;
        background: transparent;
        border: none;
        border-radius: 0;

        &:focus {
          border-color: transparent;
        }
      }
    }

    .el-form-item__error {
      color: #dd4f42;
    }

    .login-btn-wrapper {
      text-align: left;

      &:hover {
        opacity: 0.8;
      }
    }

    .login-btn {
      width: 100%;
      height: 40px;
      font-size: 18px;
      background-color: var(--color-primary);
      background-image: none;
      border: none;
      border-radius: 8px;
      box-shadow: none;
    }

    .forget-password {
      flex: 1 1 auto;
      padding-right: 10px;
      color: var(--color-primary);
      font-weight: bold;
      text-align: right;
    }

    .el-icon-user {
      width: 30px;
      height: 30px;
      font-size: 26px;
      line-height: 26px;
      text-align: center;
    }

    .float-btn {
      position: absolute;
      right: 50px;
      bottom: 40px;
      z-index: 10;
      padding: 10px;
      color: white;
      background-image: linear-gradient(135deg, var(--color-primary) 0%, #6aaeef 100%);
      border-radius: 50%;
      box-shadow: 2px 7px 12px rgba(0, 0, 0, 0.3);
      cursor: pointer;
    }
  }
</style>
